package com.itqn.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("Filter初始化方法");
    }

    public void destroy() {
        System.out.println("Filter销毁方法");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //chain.doFilter(request, response);
        System.out.println("Filter执行方法");
        HttpServletRequest request1= (HttpServletRequest) request;
        String path = request1.getServletPath().toString();
        System.out.println("当前请求的路径是:"+path);
        if (path.equals("/admin/login.jsp")||path.equals("/LoginServlet")){
            //不需要拦截
            chain.doFilter(request,response);
        }else {
            //判断session对象中有没有值
            HttpSession session = request1.getSession();
            if (session.getAttribute("login")!=null){
                //如果满足上面的条件登录成功放行
                System.out.println("登录成功!");
                chain.doFilter(request,response);
            }else {
                ((HttpServletResponse) response).sendRedirect("/admin/login.jsp");
            }
        }
    }
}
